package com.xcc.dataStructures.leetcode;


/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串""。
 *
 * 示例1:
 *
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Demo008_LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flow","flight"};
//        String[] strs = new String[]{"dog","racecar","car"};
        System.out.println(longestCommonPrefix(strs));
    }

    /**
     * 优化
     */
    public static String commonPre(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String common = strs[0];
        for (int i = 1; i < strs.length; i++) {
            if (!strs[i].startsWith(common)) {
                common = common.substring(0, common.length() - 1);
                i--;
            }
        }
        return common;
    }

    /**
     * 基础
     */
    public static String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length==0){
            return "";
        }
        String common = strs[0];
        int j;
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i < strs.length; i++) {
            j = 0;
            sb.delete(0, sb.length());
            if ("".equals(common)) {
                return "";
            }
            String str = strs[i];
            while (j < str.length() && j < common.length() && str.charAt(j) == common.charAt(j)) {
                sb.append(common.charAt(j));
                j++;
            }
            common = sb.toString();
        }
        return common;
    }
}
